import { useEffect, useRef, useState } from "react"
import HomePage_ModalComponent from "../../../../component/modal"
import lessModule from "./index.module.less"
import HomePage_SystemSettingsPage_AccountManagementPage_SideMenuComponnet from "./component/sideMenu"
import { $eventBus, $EventBus_off, $EventBus_on, $FilterOrganizationRank, $PowerSetting } from "../../../../../../common/utils"
import HomePage_TableComponent from "../../../../component/table"
import { $Http } from "../../../../../../network"

import { Divider, message } from "antd"
import HomePage_SystemSettingsPage_AccountManagementPage_ModalComponnet from "./component/modal"
import HomePage_ModalComponent_ConfirmationModallComponent from "../../../../component/modal/component/confirmationModal"

// 主页-系统设置页面-账号管理页面
const HomePage_SystemSettingsPage_AccountManagementPage = () => {
    const initParamsData = useRef<object>({})
    const paramsData = useRef<object>({})
    let [pageNo, setPageNo] = useState<number>(1)
    let [pageSize, setPageSize] = useState<number>(10)
    const [sourceData, setSourceData] = useState<object>({})


    const columnList = [
        {
            title: '序号',
            width: 60,
            render: (text: string, record: object, idx: number) => idx + 1,
        },
        {
            title: '账号名',
            minWidth: 70,
            dataIndex: 'username',
            render: (text: string) => text ?? "-"
        },
        {
            title: '性别',
            minWidth: 60,
            dataIndex: 'gender',
            render: (text: string) => text ?? "-"
        },
        {
            title: '联系电话',
            minWidth: 85,
            dataIndex: 'tel',
            render: (text: string) => text ?? "-"
        },
        {
            title: '权限',
            minWidth: 60,
            dataIndex: 'power',
            render: (text: string) => text ?? "-"
        },
        {
            title: '最后修改账号',
            minWidth: 120,
            dataIndex: 'alterName',
            render: (text: string) => text ?? "-"
        },
        {
            title: '最后修改时间',
            minWidth: 120,
            dataIndex: 'alterTime',
            render: (text: string) => text ?? "-"
        },

    ];

    const operationData = {
        title: '操作',
        align: "right",
        width: 110,
        fixed: "right",
        render: (text: string, record: object, idx: number) => <>
            {
                $PowerSetting(record["id"])["userOperation"] && <>
                    <span className="homePage-tableOperationBtn" onClick={() => click_operationTable("编辑", record)}>编辑</span>
                    <Divider className="homePage-tableOperationDivider" type="vertical" />
                    <span className="homePage-tableOperationBtn" onClick={() => click_operationTable("删除", record)}>删除</span>
                </>
            }
        </>


    }

    const [isModal, setIsModal] = useState<boolean>(false)
    const [isDeleteModal, setIsDeleteModal] = useState<boolean>(false)
    const [modalData, setModalData] = useState<object>({})

    const click_operationTable = (value: string, data: object) => {
        if (value === "删除") {
            setIsDeleteModal(true)
            setModalData({ id: data["id"], username: data["username"], rank: "账号" })
        } else {
            setIsModal(true)
            setModalData({ operation: value, rank: "账号", ...data })
        }
    }

    const change_pagination = (no: number, size: number) => {
        pageNo = no
        pageSize = size
        setPageNo(pageNo)
        setPageSize(pageSize)
        http_search()
    }

    const http_search = () => {
        $Http("search", { typeName: "系统设置/账号管理", ...paramsData.current, pageNo, pageSize }).then((res) => {
            setSourceData({ ...res["data"] })
        })
    }

    const emit_headerOperationConditionSwitch = () => {
        setTimeout(() => {
            $eventBus.emit("headerOperationConditionSwitch", { source: "HomePage_SystemSettingsPage_AccountManagementPage", explain: "请关闭头部操作条件，并查询", data: { isOpen: false } })
        });
    }

    // 广播函数数据
    const eventBusFuncData = {
        // 组织操作弹窗
        openOrganizatioOperationModal: (data: object) => {
            if (data["data"]["operation"] === "删除") {
                setIsDeleteModal(true)
                setModalData(data["data"])
            } else {
                setIsModal(true)
                setModalData(data["data"])
            }
        },
        // 选中的组织
        selectedOrganization: (data: object) => {
            paramsData.current["positionID"] = data["data"]["id"]
            emit_headerOperationConditionSwitch()
        },
        // 头部操作初始参数
        headerOperationInitParamsData: (data: object) => {
            initParamsData.current = { ...data["data"]["initParamsData"] }
            paramsData.current = { ...paramsData.current, ...data["data"]["initParamsData"] }
        },
        // 头部操作查询
        headerOperationSearch: (data: object) => {
            pageNo = 1
            setPageNo(pageNo)
            paramsData.current = { ...paramsData.current, ...data["data"]["paramsData"] }
            http_search()
        },

        // 头部操作条件的开关
        headerOperationConditionSwitch: (data: object) => {
            if (!data["data"]["isOpen"]) {
                pageNo = 1
                setPageNo(pageNo)
                paramsData.current = { ...paramsData.current, ...initParamsData.current }
                http_search()
            }
        },
        // 确认删除
        confirmOperation: (data: object) => {
            data["data"]["rank"] === "账号" && $Http("delete", { typeName: "系统设置/账号管理", id: data["data"]["id"], username: data["data"]["username"], rank: $FilterOrganizationRank(data["data"]["rank"]) }).then((res) => {
                message.success(res["success"])
                emit_headerOperationConditionSwitch()
            })
            setIsDeleteModal(false)
        },
        // 头部操作新增
        headerOperationAdd: (data: object) => {
            setIsModal(true)
            setModalData({ operation: "新建", rank: "账号" })
        }
    }



    useEffect(() => {
        $EventBus_on(eventBusFuncData)
        return () => {
            $EventBus_off(eventBusFuncData)
        }
    }, [])

    return (
        <div className={lessModule["homePageSystemSettingsPageAccountManagementPage"]}>
            <div className={lessModule["homePageSystemSettingsPageAccountManagementPage-menu"]}>
                <HomePage_SystemSettingsPage_AccountManagementPage_SideMenuComponnet />
            </div>
            <div className={lessModule["homePageSystemSettingsPageAccountManagementPage-table"]}>
                <HomePage_TableComponent name="homePageSystemSettingsAccountManagementPageTable" columnList={$PowerSetting()["superPower"] ? [...columnList, operationData] : columnList} pageNo={pageNo} pageSize={pageSize} sourceData={sourceData} change_pagination={change_pagination} />
            </div>
            {
                isModal && <HomePage_ModalComponent change_cancel={setIsModal} contentComponent={<HomePage_SystemSettingsPage_AccountManagementPage_ModalComponnet sourceData={modalData} change_cancel={setIsModal} />} />
            }
            {
                isDeleteModal && <HomePage_ModalComponent width={500} change_cancel={setIsDeleteModal} contentComponent={<HomePage_ModalComponent_ConfirmationModallComponent title={`删除${modalData["rank"]}`} content={`确认删除 “${modalData[modalData["rank"] === "账号" ? "username" : "name"]}” 吗？`} operation="删除" sourceData={modalData} change_cancel={setIsDeleteModal} />} />
            }
        </div>
    )
}
export default HomePage_SystemSettingsPage_AccountManagementPage